package net.tw.transactional2.task.impl;

import lombok.extern.slf4j.Slf4j;
import net.tw.transactional2.task.TaskAService;
import net.tw.transactional2.task.TaskBService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Hashtable;

@Service
@Slf4j
@SuppressWarnings("unchecked")
public class TaskAServiceImpl implements TaskAService {

    @Autowired
    TaskBService taskBService;

    @Autowired
    @Qualifier("threadExchangeTable")
    Hashtable<Long, Object> threadExchangeTable;

    @Override
    public Object taskA(ProceedingJoinPoint jp) {

        Thread currentThread = Thread.currentThread();
        Long threadId = currentThread.getId();

        synchronized (currentThread) {
            try {
                taskBService.taskB(threadId, jp);
                currentThread.wait();
                Hashtable<String, Object> threadExchangeData = (Hashtable<String, Object>) threadExchangeTable.get(threadId);
                threadExchangeTable.remove(threadId);
                if (Boolean.valueOf(threadExchangeData.get("status").toString())) {
                    threadExchangeTable.put(Long.valueOf(String.valueOf(threadExchangeData.get("thread_id"))), threadExchangeData);
                }
                return ResponseEntity.ok().body(threadExchangeData);
            } catch (Throwable e) {
                return ResponseEntity.badRequest().body(e.getMessage());
            }
        }
    }
}
